﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PreeRegisterModel;
using System.Data;
using PreeRegisterDAL;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Web;

namespace PreeRegisterBLL
{
    public class OrderExeInfoBLL
    {
        /// <summary>
        /// 获取预约执行情况信息
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static OrderExeInfoResponseModel OrderUpdate(OrderExeInfoRequestModel request)
        {
            try
            {
                OrderExeInfoResponseModel orderExeInfoResponseModel = new OrderExeInfoResponseModel();
                //校验输入
                string ErrMsg = "";
                if (!VerifyInput(request, ref ErrMsg))
                {
                    return null;
                }
                if (string.Equals("2", request.body.optype))
                {
                    string[] arrid = request.body.ids.Split(new char[] { ',' });
                    orderExeInfoResponseModel = GetOrderInfo(arrid);
                }
                else if (string.Equals("1", request.body.optype))
                {
                    return null;
                }

                //foreach (string orderId in arrid)
                //{
                //    //获取预约执行情况信息
                //    orderExeInfoResponseModel = GetOrderInfo(orderId);
                //}
                return orderExeInfoResponseModel;
            }
            catch (Exception err)
            {
                throw;
            }
        }

        /// <summary>
        /// 根据科室、医生、日期或订单ID查询预约执行情况
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private static OrderExeInfoResponseModel GetOrderExe(OrderExeInfoRequestModel request)
        {
            try
            {
                OrderExeInfoResponseModel orderExeInfoResponseModel = new PreeRegisterModel.OrderExeInfoResponseModel();

                OrderExeInfoBodyModel orderExeInfoBodyModel = new PreeRegisterModel.OrderExeInfoBodyModel();

                //构造查询条件
                string strwhere = "";
                if (request.body.optype == "1")
                {
                    strwhere = string.Format(@" iDeptId={0} and iDoctorId={1} ", request.body.dept, request.body.docid);
                    string strdatewhere = "";
                    string strdate = "";
                    if (request.body.dates != "")
                    {
                        string[] arrDate = request.body.dates.Split(new char[] { ',' });
                        if (arrDate.Length > 0)
                        {
                            foreach (string date in arrDate)
                            {
                                //同煤版判断  liujia150812
                                if (VariableBLL.IFTmkyy)
                                {
                                    strdate += " convert(varchar(20),dStartDate,23)='" + date + "' or";
                                }
                                else
                                {
                                    strdate += " convert(varchar(20),dStartTime,23)='" + date + "' or";
                                }
                            }
                            if (strdate.Length > 2)
                            {
                                strdate = strdate.Remove(strdate.Length - 3);
                                strdatewhere = " and (" + strdate + ")";
                            }
                        }
                    }
                    strwhere += strdatewhere;
                }
                else
                {
                    strwhere = " 1<>2 ";
                    if (request.body.ids != "")
                    {
                        string[] arrid = request.body.ids.Split(new char[] { ',' });
                        if (arrid.Length > 0)
                        {
                            string strid = "";
                            foreach (string id in arrid)
                            {
                                strid += "'" + id.Trim() + "',";
                            }
                            if (strid.Trim().Length > 0)
                            {
                                strid = strid.Remove(strid.Length - 1);
                                //同煤版判断 liujia150812
                                if (VariableBLL.IFTmkyy)
                                {
                                    strwhere += " and cPreRegisterCode in (" + strid + ")";
                                }
                                else
                                {
                                    strwhere += " and cPreeCode in (" + strid + ")";
                                }

                            }
                        }
                    }
                }
                //同煤版判断  liujia150812
                DataSet ds = OrderExeInfoDAL.GetOrderExeInfo(VariableBLL.IFTmkyy, strwhere);


                List<OrderInfoModel> OrderInfoModel_list = new List<OrderInfoModel>();

                //获取预约执行情况
                foreach (DataRow drpree in ds.Tables["opdregisterpree"].Rows)
                {
                    OrderInfoModel orderInfoModel = new OrderInfoModel();

                    orderInfoModel.oid = drpree["cPreeCode"].ToString();
                    orderInfoModel.state = drpree["bRegisteFlag"].ToString();

                    OrderInfoModel_list.Add(orderInfoModel);
                }

                orderExeInfoBodyModel.hospid = VariableBLL.HospitalId;
                orderExeInfoBodyModel.orders = OrderInfoModel_list;

                orderExeInfoResponseModel.head = VariableBLL.GetHead();
                orderExeInfoResponseModel.body = orderExeInfoBodyModel;

                return orderExeInfoResponseModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取预约执行情况
        /// </summary>
        /// <returns></returns>
        public static OrderInfoModel GetParentInfo(string orderId)
        {
            try
            {
                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"OrderId\":\"{0}\",", orderId);
                body.Append("}");
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                JObject obj = CommonBLL.HttpPost_CZHP(url);

                OrderExeInfoBodyModel orderInfoRequestModel = new OrderExeInfoBodyModel();
                orderInfoRequestModel.hospid = VariableBLL.HospitalId;

                OrderInfoModel orderInfo = new OrderInfoModel();
                string code = obj["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    var mJObj = JArray.Parse(obj["result"].ToString());
                    foreach (var drv in mJObj)
                    {
                        orderInfo.state = CommonBLL.ConvertState(drv["WorkDetail"]["AppointmentState"].ToString());
                        orderInfo.oid = drv["WorkDetail"]["PrescriptionCode"].ToString();

                        orderInfo.addr = drv["Patient"]["Address"].ToString();
                        orderInfo.birth = drv["Patient"]["Birthday"].ToString();
                        orderInfo.card = drv["Patient"]["IdentityCard"].ToString();
                        orderInfo.gender = drv["Patient"]["Gender"].ToString();
                        orderInfo.patientId = drv["Patient"]["IdentityCard"].ToString();
                        orderInfo.doctorid = drv["WorkSchedule"]["Doctor"]["DoctorCode"].ToString();

                        orderInfo.iid = drv["WorkDetail"]["Code"].ToString();
                        orderInfo.name = drv["Patient"]["PatientName"].ToString();
                        orderInfo.tel = drv["Patient"]["Telephone"].ToString();
                        orderInfo.source = drv["AppointmentSource"].ToString();
                    }
                }
                return orderInfo;
            }
            catch (Exception err)
            {
                string pathright = "error_GetOrderInfo";
                using (FileStream fst1 = new FileStream(pathright, FileMode.Append))
                {
                    using (System.IO.StreamWriter _writer1 = new System.IO.StreamWriter(fst1))
                    {
                        _writer1.WriteLine(string.Format("预约号:{0}\r\n{1}", orderId, err.ToString()));
                        _writer1.Close();
                        fst1.Close();
                    }
                }
                throw;
            }
        }

        /// <summary>
        /// 获取预约执行情况
        /// </summary>
        /// <returns></returns>
        public static OrderExeInfoResponseModel GetOrderInfo(string orderId)
        {
            try
            {
                OrderExeInfoResponseModel orderExeInfoResponseModel = new PreeRegisterModel.OrderExeInfoResponseModel();
                OrderExeInfoBodyModel orderExeInfoBodyModel = new PreeRegisterModel.OrderExeInfoBodyModel();

                string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                CommonBLL.WriteLog("1：Order|update|Post|\r\n" + url + "\r\n\r\n");
                StringBuilder head = new StringBuilder();
                StringBuilder body = new StringBuilder();
                head.Append("{head:\"\"");
                body.Append("{");
                body.AppendFormat("\"OrderId\":\"{0}\",", orderId);
                body.Append("}");
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "1：订单更新接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                postData += "\"}";
                url += postData;
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "2：订单更新接口请求密文：\r\n" + url);
                JObject obj = CommonBLL.HttpPost_CZHP(url);
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "3：订单更新接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj.ToString()));

                OrderExeInfoBodyModel orderInfoRequestModel = new OrderExeInfoBodyModel();
                orderInfoRequestModel.hospid = VariableBLL.HospitalId;

                string code = obj["code"].ToString();
                if (string.Equals(code, "1"))
                {
                    var mJObj = JArray.Parse(obj["result"].ToString());
                    List<OrderInfoModel> orders = new List<OrderInfoModel>();
                    foreach (var drv in mJObj)
                    {
                        OrderInfoModel order = new OrderInfoModel();
                        order.state = CommonBLL.ConvertState(drv["WorkDetail"]["AppointmentState"].ToString());
                        order.oid = drv["WorkDetail"]["PrescriptionCode"].ToString();
                        orders.Add(order);
                    }
                    orderExeInfoBodyModel.hospid = VariableBLL.HospitalId;
                    orderExeInfoBodyModel.orders = orders;

                    orderExeInfoResponseModel.head = VariableBLL.GetHead();
                    orderExeInfoResponseModel.body = orderExeInfoBodyModel;
                }
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, obj["msg"].ToString());
                return orderExeInfoResponseModel;
            }
            catch (Exception err)
            {
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, err.ToString());
                throw;
            }
        }

        /// <summary>
        /// 获取预约执行情况
        /// </summary>
        /// <returns></returns>
        public static OrderExeInfoResponseModel GetOrderInfo(string[] orderIds)
        {
            try
            {
                OrderExeInfoResponseModel orderExeInfoResponseModel = new PreeRegisterModel.OrderExeInfoResponseModel();
                OrderExeInfoBodyModel orderExeInfoBodyModel = new PreeRegisterModel.OrderExeInfoBodyModel();
                List<OrderInfoModel> orders = new List<OrderInfoModel>();
                foreach (string orderId in orderIds)
                {
                    string url = CommonBLL.GetConfig("CZHP_ADDR") + "GetAppointmentByOrderId?parameters=";
                    StringBuilder head = new StringBuilder();
                    StringBuilder body = new StringBuilder();
                    head.Append("{head:\"\"");
                    body.Append("{");
                    body.AppendFormat("\"OrderId\":\"{0}\",", orderId);
                    body.Append("}");
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "1：订单更新接口请求body明文：\r\n" + CommonBLL.ConvertJsonString(body.ToString()));
                    string postData = string.Format("{0},body:\"{1}", head.ToString(), HttpUtility.UrlEncode(Security.Base64.EncodeBase64(body.ToString())));
                    postData += "\"}";
                    url += postData;
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "2：订单更新接口请求密文：\r\n" + url);
                    JObject obj = CommonBLL.HttpPost_CZHP(url);
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, "3：订单更新接口返回明文：\r\n" + CommonBLL.ConvertJsonString(obj.ToString()));

                    string code = obj["code"].ToString();
                    if (string.Equals(code, "1"))
                    {
                        var mJObj = JArray.Parse(obj["result"].ToString());
                        foreach (var drv in mJObj)
                        {
                            OrderInfoModel order = new OrderInfoModel();
                            order.state = CommonBLL.ConvertState(drv["WorkDetail"]["AppointmentState"].ToString());
                            order.hospstate = drv["WorkDetail"]["AppointmentState"].ToString();
                            order.hospstateEn = drv["AppointmentOrder"]["Status"].ToString();
                            order.oid = drv["AppointmentOrder"]["OrderId"].ToString() == "" ? orderId : drv["AppointmentOrder"]["OrderId"].ToString();
                            orders.Add(order);
                        }
                    }
                    CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, obj["msg"].ToString());
                }
                orderExeInfoBodyModel.orders = orders;
                orderExeInfoBodyModel.hospid = VariableBLL.HospitalId;

                orderExeInfoResponseModel.head = VariableBLL.GetHead();
                orderExeInfoResponseModel.body = orderExeInfoBodyModel;

                return orderExeInfoResponseModel;
            }
            catch (Exception err)
            {
                CommonBLL.WriteFile_New(CommonBLL.bizCode_orderUpdate, err.ToString());
                throw;
            }
        }

        /// <summary>
        /// 校验输入参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="ErrMsg"></param>
        /// <returns></returns>
        private static bool VerifyInput(OrderExeInfoRequestModel request, ref string ErrMsg)
        {
            try
            {
                if (request.body.optype.Trim() == "")
                {
                    ErrMsg = "查询方式不能为空！";
                    return false;
                }
                if (request.body.optype.Trim() == "1")
                {
                    if (request.body.dept.Trim() == "")
                    {
                        ErrMsg = "科室ID不能为空！";
                        return false;
                    }

                    if (request.body.docid.Trim() == "")
                    {
                        ErrMsg = "医生ID不能为空！";
                        return false;
                    }
                }
                if (request.body.optype.Trim() == "2")
                {
                    if (request.body.ids.Trim() == "")
                    {
                        ErrMsg = "预约订单ID不能为空！";
                        return false;
                    }
                }
                return true;
            }
            catch (Exception err)
            {

                throw;
            }
        }

        /// <summary>
        /// 反序列化请求字符串
        /// </summary>
        /// <param name="head_json"></param>
        /// <param name="body_json"></param>
        /// <returns></returns>
        public static OrderExeInfoRequestModel ReturnOrderExeRequestModel(string head_json, string body_json)
        {
            try
            {
                Head head = csSerialize.RequestHeadInfo(head_json);

                OrderExeInfoModel body = csSerialize.OrderExeRequestBodyInfo(body_json);

                OrderExeInfoRequestModel orderExeInfoRequestModel = new OrderExeInfoRequestModel();
                orderExeInfoRequestModel.head = head;
                orderExeInfoRequestModel.body = body;
                return orderExeInfoRequestModel;
            }
            catch (Exception err)
            {

                throw;
            }
        }
    }
}
